import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { useMemo } from "react";
import { clearObject } from "./index";
/*
 * 返回页面url中，指定的键的参数值
 * */
export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams] = useSearchParams();
  const setSearchParams = useSetUrlSearchParam();
  return [
    useMemo(
      () =>
        keys.reduce((prev, key) => {
          return { ...prev, [key]: searchParams.get(key) || "" };
        }, {} as { [key in K]: string }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [searchParams]
    ),
    (params: Partial<{ [key in K]: unknown }>) => {
      return setSearchParams(params);
    },
  ] as const;
};

// export const useUrlQueryParam = <K extends string>(keys: K[]) => {
// const [stateKeys] = useState(keys)
//   const [searchParams, setSearchParams] = useSearchParams();
//   return [
//     useMemo(
//         () =>
//             keys.reduce((prev, key) => {
//               return {...prev, [key]: searchParams.get(key) || ""};
//             }, {} as { [key in K]: string }),
//         // eslint-disable-next-line react-hooks/exhaustive-deps
//         [searchParams]
//     ),
//     // setSearchParams
//     (params: Partial<{ [key in K]: unknown }>) => {
//       const o = clearObject({
//         ...Object.fromEntries(searchParams),
//         ...params,
//       }) as URLSearchParamsInit;
//       return setSearchParams(o);
//     },
//   ] as const;
// };

export const useSetUrlSearchParam = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  return (params: { [key in string]: unknown }) => {
    const o = clearObject({
      ...Object.fromEntries(searchParams),
      ...params,
    }) as URLSearchParamsInit;
    return setSearchParams(o);
  };
};

// export const useProjectsSearcgParams = () => {
//   const [param, setParam] = useUrlQueryParam(["name", "personId"]);
//   return [
//     useMemo(
//         () => ({ ...param, personId: Number(param.personId) || undefined }),
//         [param]
//     ),
//     setParam,
//   ] as const;
// };
